package Airport;

import Airport.Flight.*;

public class Airport {

	private Flight[] flights;
	public Flight[] getFlights() {
		return flights;
	}

	
	public Airport(int flightsCount) {
		
		super();
		
		if (flightsCount < 0) flightsCount = 0;
		flights = new Flight[flightsCount];
	}
	
	
	public void addFlight(Flight flight) {
		
		int freePlace = getFreePlaceForFlight();
		if (flight != null && !containsFlight(flight) && freePlace >= 0) {
			flights[freePlace] = flight;
		} else {
			System.out.println("Can't add flight");
		}
	}
	public void removeFlight(Flight flight) {
		
		if (flight != null && containsFlight(flight)) {
			for (int i=0; i<flights.length; i++) {
				if (flights[i] == flight) {
					flights[i] = null;
					break;
				}	
			}
		} else {
			System.out.println("Can't remove flight");
		}
	}
	
	
	public void cancelFlight(Flight flight) {
		
		if (containsFlight(flight)) {
			flight.setType(FlightType.CanceledFlight);
		} else {
			System.out.println("This flight does not exist.");
		}
	}
	public void openFlight(Flight flight) {
		
		if (containsFlight(flight)) {
			flight.setType(FlightType.OpenFlight);
		} else {
			System.out.println("This flight does not exist.");
		}
	}
	public void delayFlight(Flight flight) {
		
		if (flight != null && containsFlight(flight)) {
			flight.setType(FlightType.DelayFlight);
		} else {
			System.out.println("This flight does not exist.");
		}
	}
	
	
	public void addPassenger(Flight flight, Passenger passenger) {
		if (containsFlight(flight))
			flight.addPassenger(passenger);
	}
	public void removePassenger(Flight flight, Passenger passenger) {
		if (containsFlight(flight))
			flight.removePassenger(passenger);
	}
	
	
	private boolean containsFlight(Flight flight) {
		
		if (flight == null) return false;
		
		for (Flight tempflight : flights) {
			if (flight == tempflight) return true;
		}
		return false;
	}
	private int getFreePlaceForFlight() {
		
		for (int i=0; i<flights.length; i++) {
			if (flights[i] == null) return i;
		}
		return -1;
	}
	
	@Override
	public String toString() {
		
		StringBuilder strBld = new StringBuilder();
		for (Flight flight : flights) {
			if (flight != null)
				strBld.append(flight.toString() + "\n");
		}
		if (strBld.length() != 0)
			strBld.deleteCharAt(strBld.length()-1);
		
		return strBld.toString();
	}
	
}
